package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.commen.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.IUserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.TimeoutUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void sendMsg(User user, HttpServletRequest request) {
        String phone = user.getPhone();
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        log.info("验证码为：{}",code);
//        SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",phone,code);
//        request.getSession().setAttribute(phone,code);
        //将验证码设置到redis中
        redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
    }

    @Override
    public R<User> login(Map map, HttpServletRequest request) {
        String phone = (String) map.get("phone");
        String code = (String) map.get("code");
//        Object codeInSession = request.getSession().getAttribute(phone);

        //将验证码从redis取出
        Object codeInSession = redisTemplate.opsForValue().get(phone);
        if (codeInSession != null && codeInSession.equals(code)) {

            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone, phone);
            User user = this.getOne(lqw);
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                this.save(user);
            }
            request.getSession().setAttribute("user", user.getId());
            //登录成功后删除该验证码
            redisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("短信发送失败..");
    }


}
